﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MiddlewareCore
{
    /// <summary>
    /// 中间上下文
    /// 可继承此类，实现具体的请求返回统一模型处理，具体中间处理时，进行拆箱操作，执行具体的中间件操作
    /// 
    /// </summary>
    public class MiddlewareContext
    {
        /// <summary>
        /// tokenid
        /// </summary>
        public string Token { get; set; }
        /// <summary>
        /// 单个连接ID
        /// </summary>
        public string SessionId { get; set; }
        /// <summary>
        /// 主类型
        /// </summary>
        public ushort MainType { get; set; }
        /// <summary>
        /// 子类型
        /// </summary>
        public ushort SubType { get; set; }
    }
    /// <summary>
    /// 中间上下文
    /// </summary>
    /// <typeparam name="T">用户自行定义统一的数据包</typeparam>
    public class MiddlewareContext<T> : MiddlewareContext
    {
        /// <summary>
        /// 完整数据包，用户定义的统一数据包对象
        /// </summary>
        public T Data { get; set; }
    }

    public static class MiddlewareExtension
    {
        /// <summary>
        /// 获取中间件上下文自定义的统一数据模型
        /// </summary>
        /// <typeparam name="T">自定义统一模型类</typeparam>
        /// <param name="context">MiddlewareContext</param>
        /// <returns></returns>
        public static T GetData<T>(this MiddlewareContext context)
        {
            if (null == context)
                return default(T);
            try
            {
                MiddlewareContext<T> context1 = context as MiddlewareContext<T>;
                return context1.Data;
            }
            catch { return default(T); }
        }
    }

}
